Tuesday 10 January 2023

Append values in a NumPy array without defining index value



In some cases you may have to append values to a NumPy array in for loop without knowing the the number of values. Usually, NumPy arrays need to be defined before appending. But, if we don't know how many values will come from for loop, it is difficult to define an array in the beginning.

For example,

Suppose you have an array data_temp. Its values changes in every iteration and you have to append the values in data_temp to the array data row wise. 

Suppose the data_temp has 5 columns. Then first define the array data with one row and five columns.

data = numpy.empty((1,10),dtype=float)

Now get values of data_temp. For example, from a for loop. Use numpy.append to perform append. See the following code.

for i in files:

        loc, data_temp = readdata(filepath)

        data = numpy.append(data, data_temp, axis=0)


Now you will have an array data with an excess row in the beginning. So, delete that row using the code

data = numpy.delete(data,0,0)

That's all!



Code:


data = numpy.empty((1,10),dtype=float)

for i in files:

        loc, data_temp = readdata(filepath)

        data = numpy.append(data, data_temp, axis=0)

data = numpy.delete(data,0,0)

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...